#!/usr/bin/env python
#
# TODO
# - turn all the different dictionaries and lists of information floating around
#   into proper classes that can be easily passed into function
# - add license headers to all files
# - make a real TODO file
# - add docstrings to all functionsA
# Info about crash logs: http://developer.apple.com/technotes/tn2004/tn2123.html

import os, sys, signal
from globvars import *
from launcher import *
from downloader import *
from analyzer import *
from optparse import OptionParser

def signal_handler(signal, frame):
    sys.exit(0)
        
signal.signal(signal.SIGINT, signal_handler)

usage = "%prog BUILD [pd] - launches/downloads Opera build"

parser = OptionParser(usage)
parser.add_option("-g", "--getonly", action="store_true",
                  dest="get", help="downloads but doesn't launch build")
parser.add_option("-v", "--verbose", action="store_true",
                  dest="verbose", help="verbose output")
parser.add_option("-b", "--builddir", action="store",
                  type="string", dest="builddir")
parser.add_option("-u", "--user", action="store",
                  type="string", dest="user")
parser.add_option("-p", "--password", action="store",
                  type="string", dest="password")
parser.add_option("-r", "--regtest", action="store_true",
                  dest="regtest", help="[start]:[stop] [prefssuffix]")
parser.add_option("-c", "--check", action="store_true",
                  dest="check")
parser.add_option("-a", "--analyze", action="store_true",
                  dest="analyze")
parser.add_option("", "--version", action="store_true",
                  dest="version")
parser.add_option("-o", "--out", action="store",
                  type="string", dest="outfile")

(options, args) = parser.parse_args(sys.argv)

if options.version is True:

    print "cla -- version %s" % cla_version
    sys.exit(0)


if __name__ == '__main__':

    # load our preferences file and dump it into the dictionary prefdict
    try:
        prefdict = load_prefs()
    except:
        if not options.builddir:
            print "Please configure with -b, -u and -p"
            sys.exit(0)
        else:
            pass

    
    options_modified = False
    # if we are setting the builddir, we are also expected to set the username
    # and password. 
    if options.builddir:
        #     if options.user is None or options.password is None:
        #         print "You need to supply --user and --password too!"
        #         sys.exit(1)
        #     else:
        if os.path.exists(options.builddir):
            prefdict = {'builddir':options.builddir}
            options_modified = True
        else:
            print "Faulty directory %s provided." % options.builddir
            print "Aborting..."
            sys.exit(1)
            
    
    if options.user:
        prefdict['USER'] = options.user
        options_modified = True
    if options.password:
        prefdict['PASS'] = options.password
        options_modified = True
        if not options.user:
            print "No use in supplying a password without a username, aborting..."
            sys.exit(1)
        pickle_prefs(prefdict)

    if options_modified is True:
        pickle_prefs(prefdict)
        sys.exit(1)
        

    # very naive command line argument check, probably fails in some cases
    # TODO: make it better
    if len(args) < 2:
        parser.print_help()
        sys.exit(1)

        # variable that gets set True whenever user calls for a slice,
        # ie "ol [4573:4579]
        

    BUILD = args[1]
    BUILDS = []
    
    if options.regtest is True:
        
        if len(args) > 2:
            specifiedpd = args[2].replace(" ", "\ ")
        else:
            specifiedpd = None

        builds = BUILD.split(":")
        if len(builds) is not 2:
            print "Needs more arguments!"
            sys.exit(1)
        else:
            print "Starting regression test between builds", builds
            regtest(builds, list_builds(prefdict), prefdict, options,
                    specifiedpd, first=True)
            sys.exit(0)
    
    # if we are passed a slice, build a proper list called BUILDS
    # TODO: none of the functions support a list of builds yet
    if ':' in BUILD:
        BUILDS = [str(entry) for entry in range(int(BUILD.split(":")[0]),
                                                int(BUILD.split(":")[1]) + 1)]
        #print BUILDS
    else:
        BUILDS.append(BUILD)

    if options.analyze is True:
        analyze(args, options)
        sys.exit(0)
    else:
#         for single_build in BUILDS:
        #             launchbuild(single_build)

        if len(args) > 2:
            specifiedpd = args[2].replace(" ", "\ ")
        else:
            specifiedpd = None
        
        # this is a list of return values from launchbuild(..), I wonder
        # if we can do something productive with this
        launch_list = [launchbuild(build, prefdict, options, specifiedpd) for
                       build in BUILDS]

        sys.exit(0)
        
